package controllers.batch;

import controllers.admin.permission.AuthorityController;
import controllers.deadbolt.RestrictedResource;
import models.batchlist.TutorBatch;
import models.batchlist.TutorList;
import models.permission.User;
import models.tutor.Tutor;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.omg.CORBA.Object;
import play.db.jpa.JPA;
import play.modules.router.Get;
import play.modules.router.Post;
import utils.JSON;

import javax.persistence.Query;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import utils.R;


@RestrictedResource(name="/tts/batch")
public class Batchlist extends AuthorityController {

    @Get("/tts/batch")
    public static void batch() {  render();  }

    @Get("/tts/batch/data")
    public static void getBatchsData() {
        List<TutorBatch> batchs = TutorBatch.findAll();
        renderJSON(JSON.customExpose().toJson(batchs));
    }

    @Get("/tts/batch/lists/{id}")
    public static void getListsByBatchId(long id){
        List<TutorList> tutorLists = TutorList.find("byBatchid", id).fetch();
        renderJSON(JSON.customExpose().toJson(tutorLists));
    }

    @Get("/tts/batch/list/{id}")
    public static void getListById(long id) {
        TutorList list = TutorList.findById(id);
        renderJSON(JSON.customExpose().toJson(list));
    }

    @Post("/tts/batch/editlist")
    public static void editListById(TutorList list) {
        try{
            User currentUser = currentUser();
            list.lastUpdateDate = new Date();
            list.lastUpdater = currentUser.userName;
            list.save();
            R r = R.ok();
            renderJSON(r);
        }catch(Exception e) {
            error(e.getMessage());
        }
    }

    @Post("/tts/batch/add")
    public static void addbatch(String year) {
        TutorBatch batch = TutorBatch.find("byBatchyear",year).first();
        if(batch==null){
            batch = new TutorBatch();
            batch.batchyear = year;
            batch.isOpen = true;
            batch.status = true;
            batch.save();
        }
    }

    @Post("/tts/batch/toggle")
    public static void toggle(long id) {
        TutorBatch batch = TutorBatch.findById(id);
        if(batch!=null){
            batch.isOpen = !batch.isOpen;
            batch.save();
        }
    }

    /**
     * 导出导师名单上传模板
    @Get("/batch/getBatchTemplate")
    public static void getBatchTemplate(){
        VirtualFile xlsFile;
        for (VirtualFile vf : Play.javaPath) {
            xlsFile = vf.child("public/template/batchTemplate.xls");
            if (xlsFile != null && xlsFile.exists()) {
                File file = xlsFile.getRealFile();
                renderBinary(file);
                break;
            }
        }
    }
     */

    /**
     * 导入导师名单信息，重复上新纪录，而是覆盖前次上传结果。
     */
    @Post("/tts/batch/upload")
    public static void uploadTutors(long id, File file){
        try {
            //delete all old records
            TutorList.delete("batchid", id);

            //add new records
            HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
            int rows = wb.getSheetAt(0).getPhysicalNumberOfRows();
            String result = "";
            HSSFSheet sheet = wb.getSheetAt(0);
            HSSFRow row = null;
            HSSFCell cell = null;

            Date today = new Date();
            String operator = currentUser().userName;

            for (int i = 1; i < rows; i++) {
                row = sheet.getRow(i);

                //get code
                cell = row.getCell((short) 0);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String code = cell.getStringCellValue().trim();

                //get name
                cell = row.getCell((short) 1);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String name = cell.getStringCellValue().trim();

                //get unit
                cell = row.getCell((short) 2);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String unit = cell.getStringCellValue().trim();

                //get direction
                cell = row.getCell((short) 3);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String direction = cell.getStringCellValue().trim();

                //get tutorType
                cell = row.getCell((short) 4);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String tutorType = cell.getStringCellValue().trim();

                //get isParttime
                String isParttime = "";
                cell = row.getCell((short) 5);
                if(cell != null){
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    isParttime = cell.getStringCellValue().trim();
                }

                TutorList vtutor = new TutorList();
                vtutor.batchid = id;
                vtutor.code = code;
                vtutor.name = name;
                vtutor.unit = unit;
                vtutor.direction = direction;
                vtutor.tutorType = tutorType;
                vtutor.isParttime = (!isParttime.isEmpty()&&isParttime.equals("是"));
                vtutor.createDate = today;
                vtutor.createUser = operator;
                vtutor.save();
            }
            renderText("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            renderText(e.getMessage());
        }
    }
}